package com.zhiyu.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.HashMap;

@Slf4j
public class JwtUtil {

    /**
     * 过期时间为15分钟
     */
    private static final long EXPIRE_TIME = 15 * 60 * 1000;

    /**
     * token私钥
     */
    private static final String TOKEN_SECRET = "2020_ZHI_YU";

    /**
     * 生成签名,15分钟后过期
     * @param userId
     * @return
     */
    public static String sign(String userId) {
        // 过期时间
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        // 私钥及加密算法
        Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
        // 设置头信息
        HashMap<String, Object> header = new HashMap<>();
        header.put("alg", "HS256");
        header.put("typ", "JWT");
        // 附带userID生成签名
        return JWT.create().withHeader(header).withClaim("userId",userId).withExpiresAt(date).sign(algorithm);
    }

    public static String verity(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);
            DateUtil.getTime(jwt.getExpiresAt());
            if (DateUtil.getTime(jwt.getExpiresAt()) < DateUtil.getCurrentTime()) {
                return "Expired";
            }
            return jwt.getClaim("userId").asString();
        } catch (IllegalArgumentException e) {
            log.error("token解析失败", e);
            return "Parsing failed";
        } catch (JWTVerificationException e) {
            log.error("token已过期", e);
            return "Expired";
        }
    }
}
